<template>
  <div class="game-room-container">
    <!-- 顶部导航 -->
    <div class="game-header">
      <div class="room-info">
        <h2>{{ currentRoom?.name || '游戏房间' }}</h2>
        <div class="room-details">
          <p class="room-code">房间代码: {{ $route.params.roomCode }}</p>
          <div class="invite-section">
            <button 
              @click="copyRoomCode" 
              class="invite-btn"
              :title="copySuccess ? '已复制!' : '点击复制房间代码'"
            >
              📋 {{ copySuccess ? '已复制!' : '复制房间代码' }}
            </button>
            <button 
              @click="shareRoom" 
              class="invite-btn share-btn"
              title="分享房间"
            >
              📤 分享房间
            </button>
          </div>
        </div>
      </div>
      
      <div class="game-status">
        <span class="status-badge" :class="gameStatus">
          {{ gameStatusText }}
        </span>
      </div>
    </div>
    
    <!-- 错误提示 -->
    <div v-if="errorMessage" class="error-banner">
      {{ errorMessage }}
    </div>
    
    <!-- 游戏主体 -->
    <div class="game-main">
      <!-- 左侧：游戏画布 -->
      <div class="canvas-section">
        <GameCanvas
          ref="gameCanvas"
          :canvas-width="800"
          :canvas-height="600"
          :game-status="gameStatus"
          :player-count="players.length"
          :max-players="currentRoom?.maxPlayers || 6"
          :winner="winner"
          @paint-action="handlePaintAction"
          @tool-changed="handleToolChanged"
        />
      </div>
      
      <!-- 右侧：玩家列表 -->
      <div class="sidebar-section">
        <PlayerList
          :players="players"
          :max-players="currentRoom?.maxPlayers || 6"
          :game-status="gameStatus"
          :remaining-time="remainingTime"
          :current-player-id="currentPlayer?.id"
          :winner="winner"
          @start-game="handleStartGame"
          @start-solo-test="handleStartSoloTest"
          @restart-game="handleRestartGame"
          @force-end-game="handleForceEndGame"
          @leave-room="handleLeaveRoom"
        />
      </div>
    </div>
    
    <!-- 连接状态指示器 -->
    <div class="connection-indicator" :class="connectionStatus">
      <span class="indicator-dot"></span>
      {{ connectionStatusText }}
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useGameStore } from '../stores/game'
import signalRService from '../services/signalRService'
import GameCanvas from '../components/GameCanvas.vue'
import PlayerList from '../components/PlayerList.vue'

const route = useRoute()
const router = useRouter()
const gameStore = useGameStore()

// 组件引用
const gameCanvas = ref(null)

// 邀请功能状态
const copySuccess = ref(false)

// 从store获取状态
const currentRoom = computed(() => gameStore.currentRoom)
const currentPlayer = computed(() => gameStore.currentPlayer)
const players = computed(() => gameStore.players)
const gameStatus = computed(() => gameStore.gameStatus)
const remainingTime = computed(() => gameStore.remainingTime)
const winner = computed(() => gameStore.winner)
const connectionStatus = computed(() => gameStore.connectionStatus)
const errorMessage = computed(() => gameStore.errorMessage)

// 计算属性
const gameStatusText = computed(() => {
  const status = gameStatus.value?.toLowerCase()
  switch (status) {
    case 'waiting': return '等待中'
    case 'playing': return '游戏中'
    case 'finished': return '已结束'
    default: return '未知状态'
  }
})

const connectionStatusText = computed(() => {
  switch (connectionStatus.value) {
    case 'connected': return '已连接'
    case 'connecting': return '连接中...'
    case 'disconnected': return '连接断开'
    default: return '未知状态'
  }
})

// 格式化时间
const formatTime = (seconds) => {
  const minutes = Math.floor(seconds / 60)
  const remainingSeconds = seconds % 60
  return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`
}

// 事件处理
const handlePaintAction = async (paintData) => {
  if (gameStatus.value?.toLowerCase() === 'playing') {
    await signalRService.sendPaintAction(paintData)
  }
}

const handleToolChanged = (tool) => {
  console.log('Tool changed:', tool)
}

const handleStartGame = async () => {
  await signalRService.startGame()
}

// 单人测试：添加虚拟玩家并同步到后端
const handleStartSoloTest = async () => {
  if (players.value.length < 2) {
    const dummy = {
      id: crypto.randomUUID(),
      nickname: `测试玩家${Math.floor(Math.random() * 1000)}`,
      color: '#98D8C8',
      area: 0,
      isOnline: true,
      joinedAt: new Date().toISOString()
    }
    gameStore.addPlayer(dummy)
    // 尝试将虚拟玩家加入房间（后端需支持）
    try {
      await signalRService.joinRoom(route.params.roomCode, dummy)
    } catch (error) {
      console.warn('无法将虚拟玩家加入房间（可能后端不支持）:', error)
    }
  }
  
  // 强制设置游戏状态为playing并启动计时器（前端测试用）
  gameStore.setGameStatus('playing')
  // 使用房间的实际游戏时长，如果没有则使用30秒测试时间
  const testDuration = currentRoom.value?.gameDuration || 30
  gameStore.setRemainingTime(testDuration)
  
  // 同时尝试通知后端开始游戏
  try {
    await signalRService.startGame()
  } catch (error) {
    console.warn('开始游戏请求失败（可能后端不支持单人测试）:', error)
  }
}

const handleRestartGame = async () => {
  await signalRService.restartGame()
}

const handleForceEndGame = async () => {
  await signalRService.forceEndGame()
}

const handleLeaveRoom = async () => {
  await signalRService.leaveRoom()
  gameStore.leaveRoom()
  router.push('/')
}

// 复制房间代码
const copyRoomCode = async () => {
  const roomCode = route.params.roomCode
  try {
    await navigator.clipboard.writeText(roomCode)
    copySuccess.value = true
    setTimeout(() => {
      copySuccess.value = false
    }, 2000)
  } catch (error) {
    // 降级方案：使用传统方法复制
    const textArea = document.createElement('textarea')
    textArea.value = roomCode
    document.body.appendChild(textArea)
    textArea.select()
    document.execCommand('copy')
    document.body.removeChild(textArea)
    copySuccess.value = true
    setTimeout(() => {
      copySuccess.value = false
    }, 2000)
  }
}

// 分享房间
const shareRoom = async () => {
  const roomCode = route.params.roomCode
  const roomName = currentRoom.value?.name || '游戏房间'
  const shareText = `🎨 邀请你加入我的涂色抢地盘游戏！\n房间名称：${roomName}\n房间代码：${roomCode}\n游戏地址：${window.location.origin}/room/${roomCode}`
  
  try {
    if (navigator.share) {
      await navigator.share({
        title: '涂色抢地盘 - 邀请',
        text: shareText,
        url: `${window.location.origin}/room/${roomCode}`
      })
    } else {
      // 降级方案：复制分享文本
      await navigator.clipboard.writeText(shareText)
      copySuccess.value = true
      setTimeout(() => {
        copySuccess.value = false
      }, 2000)
    }
  } catch (error) {
    console.error('分享失败:', error)
  }
}

// 处理远程绘制动作
const handleRemotePaintAction = (event) => {
  if (gameCanvas.value) {
    gameCanvas.value.receivePaintAction(event.detail)
  }
}

// 初始化游戏
const initializeGame = async () => {
  const roomCode = route.params.roomCode
  
  try {
    // 获取房间信息
    const response = await fetch(`/api/queries/rooms/${roomCode}`)
    if (!response.ok) {
      throw new Error('房间不存在')
    }
    
    const roomData = await response.json()
    console.log('Room data received:', roomData) // 调试日志
    
    // 设置房间信息
    const roomInfo = {
      id: roomData.roomId,
      name: roomData.name,
      status: roomData.status,
      maxPlayers: roomData.maxPlayers,
      currentPlayers: roomData.currentPlayers,
      gameDuration: roomData.gameDuration,
      createdBy: roomData.createdBy // 确保包含createdBy
    }
    console.log('Setting room info:', roomInfo) // 调试日志
    gameStore.setCurrentRoom(roomInfo)
    gameStore.setPlayers(roomData.players)
    gameStore.setGameStatus(roomData.status)
    
    // 检查当前用户是否是房主
    // 如果房间的创建者ID存在，尝试找到对应的玩家
    let currentPlayer = null
    if (roomData.createdBy) {
      currentPlayer = roomData.players.find(player => player.id === roomData.createdBy)
    }
    
    // 如果没有找到房主，或者房间没有创建者信息，使用第一个玩家
    if (!currentPlayer && roomData.players.length > 0) {
      currentPlayer = roomData.players[0]
    }
    
    // 如果还是没有找到，创建一个默认玩家
    if (!currentPlayer) {
      currentPlayer = {
        id: crypto.randomUUID(),
        nickname: `玩家${Math.floor(Math.random() * 1000)}`,
        color: getRandomColor(),
        area: 0,
        isOnline: true,
        joinedAt: new Date().toISOString()
      }
    }
    
    console.log('Setting current player:', currentPlayer) // 调试日志
    gameStore.setCurrentPlayer(currentPlayer)
    
    // 设置Canvas的玩家颜色映射
    if (gameCanvas.value) {
      const playerColors = {}
      // 设置所有玩家的颜色映射
      roomData.players.forEach(player => {
        playerColors[player.id] = player.color
      })
      gameCanvas.value.setPlayerColors(playerColors)
    }
    
    // 连接SignalR
    await signalRService.connect(roomCode, currentPlayer.id)
    
    // 加入房间
    await signalRService.joinRoom(roomCode, currentPlayer)
    
  } catch (error) {
    console.error('初始化游戏失败:', error)
    gameStore.setErrorMessage(error.message || '初始化游戏失败')
    setTimeout(() => {
      router.push('/')
    }, 2000)
  }
}

// 获取随机颜色
const getRandomColor = () => {
  const colors = [
    '#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', 
    '#FFEAA7', '#DDA0DD', '#98D8C8', '#F7DC6F'
  ]
  return colors[Math.floor(Math.random() * colors.length)]
}

// 监听远程绘制事件
const setupEventListeners = () => {
  window.addEventListener('remotePaintAction', handleRemotePaintAction)
}

const cleanupEventListeners = () => {
  window.removeEventListener('remotePaintAction', handleRemotePaintAction)
}

// 更新Canvas的玩家颜色映射
const updateCanvasPlayerColors = () => {
  if (gameCanvas.value) {
    const playerColors = {}
    players.value.forEach(player => {
      if (player.color) {
        playerColors[player.id] = player.color
      }
    })
    gameCanvas.value.setPlayerColors(playerColors)
  }
}

// 监听玩家列表变化
const watchPlayers = () => {
  updateCanvasPlayerColors()
}

onMounted(async () => {
  setupEventListeners()
  await initializeGame()
  
  // 监听玩家列表变化
  watchPlayers()
})

onUnmounted(() => {
  cleanupEventListeners()
  signalRService.disconnect()
})
</script>

<style scoped>
.game-room-container {
  min-height: 100vh;
  background: #f8f9fa;
  display: flex;
  flex-direction: column;
}

.game-header {
  background: white;
  padding: 16px 24px;
  border-bottom: 1px solid #e9ecef;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.room-info h2 {
  margin: 0 0 4px 0;
  color: #495057;
  font-size: 1.5rem;
}

.room-code {
  margin: 0;
  color: #6c757d;
  font-size: 14px;
  font-family: 'Courier New', monospace;
}

.room-details {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.invite-section {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.invite-btn {
  padding: 6px 12px;
  border: none;
  border-radius: 6px;
  font-size: 12px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
  background: #e9ecef;
  color: #495057;
  text-decoration: none;
  display: inline-flex;
  align-items: center;
  gap: 4px;
}

.invite-btn:hover {
  background: #dee2e6;
  transform: translateY(-1px);
}

.invite-btn.share-btn {
  background: #007bff;
  color: white;
}

.invite-btn.share-btn:hover {
  background: #0056b3;
}

.game-status {
  display: flex;
  align-items: center;
  gap: 16px;
}

.status-badge {
  padding: 6px 12px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 500;
}

.status-badge.waiting {
  background: #fff3cd;
  color: #856404;
}

.status-badge.playing {
  background: #d4edda;
  color: #155724;
}

.status-badge.finished {
  background: #f8d7da;
  color: #721c24;
}

.timer {
  font-size: 18px;
  font-weight: bold;
  color: #dc3545;
  font-family: 'Courier New', monospace;
}

.error-banner {
  background: #f8d7da;
  color: #721c24;
  padding: 12px 24px;
  text-align: center;
  border-bottom: 1px solid #f5c6cb;
}

.game-main {
  flex: 1;
  display: flex;
  gap: 20px;
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
  width: 100%;
}

.canvas-section {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: flex-start;
}

.sidebar-section {
  width: 320px;
  flex-shrink: 0;
}

.connection-indicator {
  position: fixed;
  bottom: 20px;
  right: 20px;
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 500;
  background: white;
  border: 1px solid #e9ecef;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.connection-indicator.connected {
  color: #155724;
}

.connection-indicator.connecting {
  color: #856404;
}

.connection-indicator.disconnected {
  color: #721c24;
}

.indicator-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: currentColor;
}

.connection-indicator.connected .indicator-dot {
  background: #28a745;
}

.connection-indicator.connecting .indicator-dot {
  background: #ffc107;
  animation: pulse 1s infinite;
}

.connection-indicator.disconnected .indicator-dot {
  background: #dc3545;
}

@keyframes pulse {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.5; }
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .game-main {
    flex-direction: column;
    align-items: center;
  }
  
  .sidebar-section {
    width: 100%;
    max-width: 600px;
  }
}

@media (max-width: 768px) {
  .game-header {
    flex-direction: column;
    gap: 12px;
    text-align: center;
  }
  
  .game-status {
    flex-direction: column;
    gap: 8px;
  }
  
  .game-main {
    padding: 10px;
    gap: 10px;
  }
  
  .canvas-section {
    width: 100%;
  }
  
  .connection-indicator {
    bottom: 10px;
    right: 10px;
    font-size: 10px;
    padding: 6px 8px;
  }
}
</style>
